﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MarkDownFileSplitter.Meilisearch.Control
{
    internal partial class IndexViewerControl : UserControl
    {
        private string m_currentIndexUid;
        /// <summary>
        /// 选择的文档
        /// </summary>
        internal IndexInfo SelectedIndexInfo { get; set; }

        public IndexViewerControl()
        {
            InitializeComponent();

            BuildContentMenu();
        }


        // 在 BuildContentMenu 方法中关联事件
        private void BuildContentMenu()
        {
            // 创建上下文菜单
            ContextMenuStrip contentMenu = new ContextMenuStrip();

            // 创建删除菜单项
            ToolStripMenuItem deleteMenuItem = new ToolStripMenuItem("删除");
            deleteMenuItem.Click += deleteMenuItem_Click;
            contentMenu.Items.Add(deleteMenuItem);

            // 创建更新菜单项
            ToolStripMenuItem updateMenuItem = new ToolStripMenuItem("更新");
            updateMenuItem.Click += updateMenuItem_Click;
            contentMenu.Items.Add(updateMenuItem);

            // 创建添加菜单项
            ToolStripMenuItem addMenuItem = new ToolStripMenuItem("添加");
            addMenuItem.Click += addMenuItem_Click;
            contentMenu.Items.Add(addMenuItem);

            // 假设这里将上下文菜单关联到某个控件，这里以 this 为例
            this.dataGridView.ContextMenuStrip = contentMenu;
        }

        // 删除菜单项点击事件
        private async void deleteMenuItem_Click(object sender, EventArgs e)
        {
            DataGridViewRow selectedRow = null;
            if (this.dataGridView.SelectedCells.Count > 0)
            {
                selectedRow = this.dataGridView.SelectedCells[0].OwningRow;
            }

            if (selectedRow != null)
            {
                string selectedId = "";
                foreach (DataGridViewCell cell in selectedRow.Cells)
                {
                    if (cell.OwningColumn.Name == this.SelectedIndexInfo.PrimaryKey)
                    {
                        selectedId = cell.Value.ToString();
                    }
                }
                if (string.IsNullOrEmpty(selectedId)) { return; }


                // 弹出消息框提醒用户是否要删除记录
                DialogResult result = MessageBox.Show($"确定要删除记录为:【{selectedId}】的记录吗？", "删除确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    var t = await MeilisearchUploader.Instance.DeleteOneDocument(m_currentIndexUid, selectedId);
                    MessageBox.Show("删除" + (t ? "成功！" : "失败!"));
                }
            }
        }

        // 更新菜单项点击事件
        private void updateMenuItem_Click(object sender, EventArgs e)
        {
            DataGridViewRow selectedRow = null;
            if (this.dataGridView.SelectedCells.Count > 0)
            {
                selectedRow = this.dataGridView.SelectedCells[0].OwningRow;
            }

            if (selectedRow != null)
            {
                StringBuilder selectedInfo = new StringBuilder();
                foreach (DataGridViewCell cell in selectedRow.Cells)
                {
                    selectedInfo.Append($"{cell.OwningColumn.Name}: {cell.Value} ");
                }
                Console.WriteLine($"选中记录的信息: {selectedInfo.ToString().Trim()}");
                // 这里可以添加删除记录的具体逻辑
            }
            else
            {
                Console.WriteLine("未选中任何记录");
            }

            MessageBox.Show("待处理.");
        }

        // 添加菜单项点击事件
        private void addMenuItem_Click(object sender, EventArgs e)
        {
            Console.WriteLine("即将添加新记录");
            // 这里可以添加添加记录的具体逻辑
            MessageBox.Show("待处理.");
        }

       

        public async void RefreshGrid(string indexUid,IndexInfo selectedIndexInfo)
        {
            m_currentIndexUid = indexUid;
            SelectedIndexInfo = selectedIndexInfo;

            // 清空DataGridView
            this.dataGridView.Rows.Clear();
            this.dataGridView.Columns.Clear();

            JArray documents = await MeilisearchUploader.Instance.GetDocuments(indexUid, 200);
            if (documents.Count == 0)
                return;

            var attrNameSet = new HashSet<string>();
            foreach (JObject doc in documents)
            {
                foreach (var prop in doc.Properties())
                {
                    attrNameSet.Add(prop.Name);
                }
            }
            List<string> attrNames = attrNameSet.ToList();

            // 根据属性名创建列
            foreach (string attrName in attrNames)
            {
                this.dataGridView.Columns.Add(attrName, attrName);
            }

            // 遍历documents添加数据行
            foreach (JObject document in documents)
            {
                int rowIndex = this.dataGridView.Rows.Add();
                foreach (string attrName in attrNames)
                {
                    this.dataGridView.Rows[rowIndex].Cells[attrName].Value = document[attrName]?.ToString();
                }
            }
        }
    }
}
